package com.segment.dcore.base.component;

import org.apache.commons.codec.binary.Base64;
import org.springframework.util.DigestUtils;

import com.alibaba.dubbo.rpc.RpcContext;

import java.util.concurrent.atomic.AtomicLong;

/**
 * RequestIDGenerator
 *
 * Created by huapeng.hhp on 2017/2/26.
 */
public class ContextIDGenerator {
	private static ContextIDGenerator contextIDGenerator = new ContextIDGenerator();

	public static ContextIDGenerator getContextIDGenerator() {
		return contextIDGenerator;
	}

	private ContextIDGenerator() {
	}

    /** 请求流水号 */
    AtomicLong number = new AtomicLong();

    /**
     * 生产上下文ID
     * @return
     */
    public String buildContextId() {
        StringBuilder md5SegmentBuilder = new StringBuilder();

        RpcContext context = RpcContext.getContext();
        String remoteHostSegment = context.getRemoteHost();
        String localHostSegment = context.getLocalHost();
        //String appName = (String) Insight.props().getString(InsightConstants.APP_NAME);

        // 远程IP
        md5SegmentBuilder.append(remoteHostSegment);
        // 本地IP
        md5SegmentBuilder.append(localHostSegment);
        // 时间
        long timeSegment = System.currentTimeMillis();
        md5SegmentBuilder.append(timeSegment);
        byte[] md5 = DigestUtils.md5Digest(md5SegmentBuilder.toString().getBytes());
        String md5Segment = Base64.encodeBase64String(md5);

        StringBuilder builder = new StringBuilder();

        // 应用名称
        //builder.append(appName).append(":");
        builder.append(md5Segment);
        // 生成流水号
        long serialNumber = number.incrementAndGet();
        builder.append(serialNumber);

        // 替换复杂字符
        String result = builder.toString();
        result = result.replace("/", "s");
        result = result.replace("+", "p");
        result = result.replace("==", "de");
        result = result.replace("=", "e");

        return result;

    }
}
